package com.czk.shop.mq;

import com.alibaba.fastjson.JSON;
import com.comon.czk.constant.ShopCode;
import com.comon.czk.entity.MQEntity;
import com.czk.shop.mapper.TradeCouponMapper;
import com.czk.shop.pojo.TradeCoupon;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/10/20 21:23
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {
    @Autowired
    private TradeCouponMapper tradeCouponMapper;

    @SneakyThrows
    @Override
    public void onMessage(MessageExt messageExt) {
        // 解析消息内容
        try {
            String body = new String(messageExt.getBody(), "UTF-8");
            MQEntity mqEntity = JSON.parseObject(body, MQEntity.class);
            // 记录日志
            log.info("接收到消息");
            if (mqEntity.getCouponId()!=null){
                // 查询优惠券信息
                TradeCoupon tradeCoupon = tradeCouponMapper.selectByPrimaryKey(mqEntity.getCouponId());
                // 更改优惠券状态
                // 将使用信息设置为未使用
                tradeCoupon.setUsedTime(null);
                //
                tradeCoupon.setIsUsed(ShopCode.SHOP_COUPON_UNUSED.getCode());
                // 设置订单id
                tradeCoupon.setOrderId(null);
                // 更新操作
                tradeCouponMapper.updateByPrimaryKey(tradeCoupon);
                log.info("回退优惠券成功");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("回退优惠券失败");
        }
    }
}
